package com.soft.leo.oldbook;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.ProgressCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.SignUpCallback;
import com.yongchun.library.view.ImageSelectorActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SignupActivity extends AppCompatActivity implements AMapLocationListener, DistrictSearch.OnDistrictSearchListener {
    public AMapLocationClientOption mLocationOption = null;
    private RadioGroup locationGroup;
    private LinearLayout locationSelect;
    private Spinner province,city,district,street;
    private CircleImageView headSelecter;
    private String lastLevel="province";
    private View popmenu;
    private PopupWindow window;
    private List<String> loveList;
    private List<String> kindList;
    private Button regbt;
    private boolean chooseImg=false;
    private RadioGroup sex;
    private String realSex="男";
    private String headUrl=null;
    private String headLocalUrl=null ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //region 浸入式标题栏
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        //endregion
        setContentView(R.layout.activity_signup);

        initComp();
        initFunc();

        initLocation();



    }

    private void initFunc() {
        locationGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i){
                    case R.id.reallocation:
                        locationSelect.setVisibility(View.GONE);
                        break;
                    case R.id.costlocation:
                        locationSelect.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });
        sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                realSex=((RadioButton)findViewById(i)).getText().toString();
            }
        });

        province.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                searchCity(adapterView.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                searchCity(adapterView.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        district.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                searchCity(adapterView.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        headSelecter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ImageSelectorActivity.start(SignupActivity.this, 1, ImageSelectorActivity.MODE_SINGLE, true,true,true);

            }
        });
        regbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final EditText name=(EditText)findViewById(R.id.nameIn);
                final EditText pwd=(EditText)findViewById(R.id.pwdIn);
                EditText pwdIn=(EditText)findViewById(R.id.surePwdIn);
                final EditText selt=(EditText)findViewById(R.id.seltIn);


                if(chooseImg==false||loveList.isEmpty()||kindList.isEmpty()||name.getText().equals("")||pwd.getText().equals("")||pwdIn.getText().equals("")||selt.getText().equals("")){
                    Toast.makeText(SignupActivity.this,"请完成所有输入",Toast.LENGTH_LONG).show();
                }else if(!(pwd.getText().toString()).equals(pwdIn.getText().toString())){
                    Toast.makeText(SignupActivity.this,"两次密码不一致",Toast.LENGTH_LONG).show();
                }else{

                            try {
                                final AVFile file  = AVFile.withAbsoluteLocalPath(name.getText().toString()+"head.png", headLocalUrl);
                                file.saveInBackground(new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        AVUser user = new AVUser();// 新建 AVUser 对象实例
                                        user.setUsername(name.getText().toString());// 设置用户名
                                        user.setPassword(pwd.getText().toString());// 设置密码
                                        user.put("self",selt.getText().toString());
                                        user.put("lovelist",loveList);
                                        user.put("kindlist",kindList);
                                        user.put("sex",realSex);
                                        user.put("money",10);
                                        user.put("url",file);
                                        if(locationSelect.isShown()){
                                            String loca="";
                                            if(province.getSelectedItem()!=null)
                                                loca=loca+province.getSelectedItem().toString();
                                            if(city.getSelectedItem()!=null)
                                                loca=loca+city.getSelectedItem().toString();
                                            if(district.getSelectedItem()!=null)
                                                loca=loca+district.getSelectedItem().toString();
                                            if(street.getSelectedItem()!=null)
                                                loca=loca+street.getSelectedItem().toString();
                                            user.put("location",loca);
                                        }else{
                                            user.put("location",((RadioButton)findViewById(R.id.reallocation)).getText().toString());
                                        }

                                        user.signUpInBackground(new SignUpCallback() {
                                            @Override
                                            public void done(AVException e) {
                                                if (e == null) {
                                                    Toast.makeText(SignupActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                                                } else {
                                                    if(e.getCode()==202)
                                                        Toast.makeText(SignupActivity.this,"用户名已存在",Toast.LENGTH_SHORT).show();
                                                    else
                                                        Toast.makeText(SignupActivity.this,e.toString(),Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });

                                    }
                                });

                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }






                }
            }
        });
    }

    private void initComp() {
        sex=(RadioGroup)findViewById(R.id.sexChoose);
        regbt=(Button)findViewById(R.id.reg_bt);
        kindList=new ArrayList<>();
        loveList=new ArrayList<>();
        locationGroup=(RadioGroup)findViewById(R.id.locationGroup);
        locationSelect=(LinearLayout)findViewById(R.id.locationSelect);
        province=(Spinner)findViewById(R.id.province);
        city=(Spinner)findViewById(R.id.city);
        district=(Spinner)findViewById(R.id.district);
        street=(Spinner)findViewById(R.id.street);
        headSelecter=(CircleImageView)findViewById(R.id.head_select_bt);
        popmenu=getLayoutInflater().inflate(R.layout.select_photo_menu, null);
    }

    private void initLocation() {
        AMapLocationClient mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setOnceLocation(true);
//设置定位监听
        mlocationClient.setLocationListener(this);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
    }
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                ((RadioButton)findViewById(R.id.reallocation)).setText(amapLocation.getProvince()+amapLocation.getCity()+amapLocation.getDistrict()+amapLocation.getStreet());
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }
    public void searchCity(String lastCity){
        DistrictSearch search = new DistrictSearch(getApplicationContext());
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords(lastCity);//传入关键字
        query.setShowBoundary(true);//是否返回边界值
        search.setQuery(query);
        search.setOnDistrictSearchListener(this);//绑定监听器
        search.searchDistrictAnsy();//开始搜索
    }

    @Override
    public void onDistrictSearched(DistrictResult districtResult) {
        List<String> list=new ArrayList<String>();
        String level=null;
        for (DistrictItem item:districtResult.getDistrict().get(0).getSubDistrict()) {
            list.add(item.getName());
            level=item.getLevel();
        }
        if (list.isEmpty()){
            if(lastLevel.equals("city")){
                district.setAdapter(null);
                street.setAdapter(null);

            }else if(lastLevel.equals("district")){
                street.setAdapter(null);
            }
            lastLevel="province";
            return;
        }
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,list);
        if(level.equals("city")){
            city.setAdapter(adapter);
        }else if(level.equals("district")){
            district.setAdapter(adapter);
        }else if(level.equals("street")){
            street.setAdapter(adapter);
        }
        lastLevel=level;
        if(lastLevel.equals("street"))
            lastLevel="province";

    }

    public void lovepart(View view){
        String str=((Button)view).getText().toString();
        if(loveList.contains(str)){
            view.setBackgroundResource(R.drawable.tag_check);
            ((Button) view).setTextColor(Color.BLACK);
            loveList.remove(str);
        }else{
            view.setBackgroundResource(R.drawable.tag_normal);
            loveList.add(str);
            ((Button) view).setTextColor(Color.WHITE);
        }
    }
    public void lovekind(View view){

        String str=((Button)view).getText().toString();
        if(kindList.contains(str)){
            view.setBackgroundResource(R.drawable.tag_check);
            ((Button) view).setTextColor(Color.BLACK);
            kindList.remove(str);
        }else{
            view.setBackgroundResource(R.drawable.tag_normal);
            kindList.add(str);
            ((Button) view).setTextColor(Color.WHITE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK && requestCode == ImageSelectorActivity.REQUEST_IMAGE) {
            ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
            try {
                FileInputStream fis = new FileInputStream(images.get(0));
                headSelecter.setImageBitmap(BitmapFactory.decodeStream(fis));
                headLocalUrl=images.get(0);
                chooseImg=true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}
